<template>
	<div class="lc_wrap">
		<el-row class="proportion">
			<div class="overlay" ref="overlay">
				<div class="tree-tool" @click="changeTreeBox">
					<div class="tool-line"></div>
					<div class="tool-line"></div>
					<div class="tool-line"></div>
				</div>
			</div>
			<el-col :span="leftWidth">
				<div class="box">
					<basic-container>
						<avue-tree ref="tree" :data="treeData" :option="treeOption" @node-click="nodeClick" />
					</basic-container>
				</div>
			</el-col>
			<el-col :span="rightWidth" class="table-wrapper">
				<basic-container>
					<div class="search-tools">
						<div class="search-left">
							<div>
								<div>
									<el-date-picker v-if="dateType==2" v-model="newDataTime" type="month" size="small" value-format="yyyy-MM" placeholder="选择月份" :picker-options="pickerOption" :clearable='false' style="margin-right:20px;" @change="changNewDataTime"></el-date-picker>

									<el-date-picker v-if="dateType==1" v-model="newDataTime2" type="date" size="small" value-format="yyyy-MM-dd" placeholder="选择日期" :picker-options="pickerOption" :clearable='false' style="margin-right:20px;" @change="changNewDataTime2"></el-date-picker>
								</div>
							</div>
							<div style="margin-left:20px;">
								<el-select size="small" v-model="gene" @change="changeYz">
									<el-option v-for="(item, index) in geneList" :key="index" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</div>
						</div>
						<div class="search-right">
							<div class="search-tabs">
								<el-radio v-model="dateType" v-for="(item, index) in dateTypeList" :key="index" :label="item.label">{{ item.value }}</el-radio>
							</div>

						</div>
					</div>
					<e-chart autoresize :options="chartOptions" style="height:92%;" ref="charts" id="charts"></e-chart>
				</basic-container>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	function getDay(num, str) {
		var today = new Date();
		var nowTime = today.getTime();
		var ms = 24 * 3600 * 1000 * num;
		today.setTime(parseInt(nowTime + ms));
		var oYear = today.getFullYear();
		var oMoth = (today.getMonth() + 1).toString();
		if(oMoth.length <= 1) oMoth = '0' + oMoth;
		var oDay = today.getDate().toString();
		if(oDay.length <= 1) oDay = '0' + oDay;
		return oYear + str + oMoth + str + oDay;
	}
	// 格式化日期
	function formatDate(date) {
		date = new Date(date);
		let myyear = date.getFullYear();
		let mymonth = date.getMonth() + 1;
		let myweekday = date.getDate();
		mymonth < 10 ? mymonth = "0" + mymonth : mymonth;
		myweekday < 10 ? myweekday = "0" + myweekday : myweekday;
		return `${myyear}-${mymonth}-${myweekday}`;
	}
	// 获取当前月的天数
	function mGetDate() {
		var date = new Date();
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var d = new Date(year, month, 0);
		return d.getDate();
	}
	// 获取本周的日期
	function getWeekDay() {
		let dateString = formatDate(new Date()); //当天的日期，例如2020-2-28
		let presentDate = new Date(dateString);
		let today = presentDate.getDay() !== 0 ? presentDate.getDay() : 7;

		return Array.from(new Array(7), function(val, index) {
			return formatDate(new Date(presentDate.getTime() - (today - index - 1) * 24 * 60 * 60 * 1000));
		});
	}
	// 获取当前月的所有日期
	function getNowM(e) {
		let now = new Date();
		let current_month_num = mGetDate();
		let current_month = [];
		for(let i = 1; i <= current_month_num; i++) {
			let day = now.setDate(i);
			let everyDay = formatDate(day);
			current_month.push(everyDay);
		}
		return current_month;
	}

	function getDaysInMonth(year, month) {
		const daysOfMonth = [];
		let dataMonth = month
		month = parseInt(month, 10);
		const lastDayOfMonth = new Date(year, month, 0).getDate();
		for(let i = 1; i <= lastDayOfMonth; i++) {
			if(i < 10) {
				daysOfMonth.push(year + "-" + dataMonth + "-" + "0" + i);
			} else {
				daysOfMonth.push(year + "-" + dataMonth + "-" + i);
			}
		}
		return daysOfMonth;
	}

	var upColor = '#00da3c';
	var downColor = '#00da3c';

	function splitData(rawData) {
		var categoryData = [];
		var values = [];
		var volumes = [];
		for(var i = 0; i < rawData.length; i++) {
			categoryData.push(rawData[i].splice(0, 1)[0]);
			values.push(rawData[i]);
			volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
		}

		return {
			categoryData: categoryData,
			values: values,
			volumes: volumes
		};
	}

	function calculateMA(dayCount, data) {
		var result = [];
		for(var i = 0, len = data.values.length; i < len; i++) {
			if(i < dayCount) {
				result.push('-');
				continue;
			}
			var sum = 0;
			for(var j = 0; j < dayCount; j++) {
				sum += data.values[i - j][1];
			}
			result.push(+(sum / dayCount).toFixed(3));
		}
		return result;
	}
	let timeArr = ['00:00', "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "24:00"]
	import { getDeptTree, getTypes, getLine, getFactorList } from "@/api/swaq/proportion";

	import { mapGetters } from "vuex";
	import { dateFormat, getPreMonth, getNextMonth, getPreYear, getPreYear2 } from "@/util/date";
	export default {
		data() {
			let _this = this
			return {
				interval: 0.5,
				newDataTime: dateFormat(new Date(), 'yyyy-MM'),
				newDataTime2: dateFormat(new Date(), 'yyyy-MM-dd'),
				chartOptions: {},
				leftWidth: this.$leftWidth,
				rightWidth: this.$rightWidth,
				loading: false,
				data: [],
				// 左侧树配置属性
				treeOption: {
					nodeKey: 'id',
					addBtn: false,
					menu: false,
					size: 'small',
					defaultExpandAll: true,
					props: {
						label: 'title',
						value: 'value',
						children: 'children'
					}
				},
				treeData: [],
				nodeId: null,
				deptInfoName: '',
				deptInfoId: '',
				dateType: 1,
				dateTypeList: [{
						label: 1,
						value: '日K线'
					},
					{
						label: 2,
						value: '月K线'
					}
				],
				pickerOption: {
					firstDayOfWeek: 1,
					disabledDate(time) {
						return _this.dateType == 3 ? false : time.getTime() > Date.now()
					},
				},
				geneList: [{
						label: '水温',
						value: 0,
						min: 15,
						max: 25
					},
					{
						label: 'pH值',
						value: 1,
						min: 6,
						max: 9
					},
					{
						label: '溶解氧',
						value: 2,
						min: 5,
						max: 7.5
					},
					{
						label: '电导率',
						value: 3,
						min: 100,
						max: 200
					},
					{
						label: '浊度',
						value: 4,
						min: 1,
						max: 3
					}
				],
				gene: 0,
				timeData: [],
				Kdata: [],
				nowMonthFirst: '',
				nowMonthLast: dateFormat(new Date(), 'yyyy-MM-dd')
			};
		},
		computed: {
			...mapGetters(["permission"]),
		},
		watch: {
			dateType(val) {
				this.onLoad()
			}
		},
		mounted() {
			let arr = this.newDataTime.split('-')
			let a = getDaysInMonth(arr[0], arr[1])
			this.nowMonthFirst = a[0]
			this.onLoad()
			this.initData()
		},
		methods: {
			changeYz(val) {
				this.onLoad()
			},
			changNewDataTime(val) {
				let arr = val.split('-')
				let arr1 = getDaysInMonth(arr[0], arr[1])
				let c = dateFormat(new Date(), 'yyyy-MM')
				if(arr1[0] == c + '-01') {

					this.nowMonthFirst = arr1[0]
					this.nowMonthLast = dateFormat(new Date(), 'yyyy-MM-dd')
				} else {
					this.nowMonthFirst = arr1[0]
					this.nowMonthLast = arr1[arr1.length - 1]
					console.log(this.nowMonthFirst)
					console.log(this.nowMonthLast)
				}
				this.onLoad()
			},
			changNewDataTime2(val) {
				this.onLoad()
			},

			/*** 初始化表单*/
			initData() {
				// 树内容接口
				getDeptTree('2').then(res => {
					this.treeData = res.data.data
					this.$nextTick(function() {
						// 获取el-tree对象
						let elTreeDom = this.$refs.tree.$children[1]
						// 获取要设置的节点-第一个最下层节点,并设置默认选中
						let firstNode = this.getFirstNode(res.data.data)
						elTreeDom.setCurrentNode(firstNode)
						this.nodeClick(firstNode)
					})
				})
			},
			changeTreeBox() {
				this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
				this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
			},
			// 搜索
			search() {
				this.onLoad()
			},
			/*** 树点击事件*/
			async nodeClick(data) {
				this.nodeId = data.key
				this.deptInfoName = data.title
				this.deptInfoId = data.key
				//          await getFactorList(this.nodeId).then(res =>{
				//              this.geneList=res.data.data;
				//              this.gene=this.geneList[0].factorCode;
				//          })
				this.onLoad()
			},
			/*** 获取第一个最下层节点*/
			getFirstNode(tree, node = null) {
				tree.forEach(item => {
					if(!node) {
						if(item.children && item.children.length) {
							node = this.getFirstNode(item.children, node)
						} else {
							node = item
						}
					}
				})
				return node
			},
			getDateBetween(start, end) {
				var result = [];
				//使用传入参数的时间
				var startTime = new Date(start);
				var endTime = new Date(end);
				while(endTime - startTime >= 0) {
					let year = startTime.getFullYear();
					let month = startTime.getMonth();
					month = month < 9 ? '0' + (month + 1) : month + 1;
					let day = startTime.getDate().toString().length == 1 ? "0" + startTime.getDate() : startTime.getDate();
					//加入数组
					result.push(year + "-" + month + "-" + day);
					//更新日期
					startTime.setDate(startTime.getDate() + 1);
				}
				return result;
			},

			formatValue(val) {
				let min = this.geneList[val].min
				let max = this.geneList[val].max
				return {
					min: min,
					max: max
				}
			},
			formatTitle(val) {
				return this.geneList[val].label
			},
			onLoad() {
				let newArr = []
				let title = this.formatTitle(this.gene)
				if(this.dateType == 1) {
					let obj = this.formatValue(this.gene)
					let arr = timeArr
					for(var i = 0; i < arr.length; i++) {
						newArr[i] = []
						if(this.gene == 0 || this.gene == 3) {
							let num1 = Math.ceil(Math.random() * (obj.max - obj.min)) + obj.min
							let num2 = Math.ceil(Math.random() * (obj.max - num1)) + num1
							newArr[i].push(arr[i], num1, Math.ceil(Math.random() * (obj.max - obj.min)) + obj.min, Math.ceil(Math.random() * (obj.max - obj.min)) + obj.min, num2, Math.floor(Math.random() * 10000))
						} else if(this.gene == 1 || this.gene == 2 || this.gene == 4) {
							let num1 = Number(((Math.random() * (obj.max - obj.min)) + obj.min).toFixed(2));
							let num2 = Number(((Math.random() * (obj.max - obj.min)) + num1).toFixed(2));
							newArr[i].push(arr[i], num1, Number(((Math.random() * (obj.max - obj.min)) + obj.min).toFixed(2)), Number(((Math.random() * (obj.max - obj.min)) + obj.min).toFixed(2)), num2, Math.floor(Math.random() * 10000))
						}
					}
				} else if(this.dateType == 2) {
					let obj = this.formatValue(this.gene)
					let arr = this.getDateBetween(this.nowMonthFirst, this.nowMonthLast)
					for(var i = 0; i < arr.length; i++) {
						newArr[i] = []
						if(this.gene == 0 || this.gene == 3) {
							let num1 = Math.ceil(Math.random() * (obj.max - obj.min)) + obj.min
							let num2 = Math.ceil(Math.random() * (obj.max - num1)) + num1
							newArr[i].push(arr[i], num1, Math.ceil(Math.random() * (obj.max - obj.min)) + obj.min, Math.ceil(Math.random() * (obj.max - obj.min)) + obj.min, num2, Math.floor(Math.random() * 10000))
						} else if(this.gene == 1 || this.gene == 2 || this.gene == 4) {
							let num1 = Number(((Math.random() * (obj.max - obj.min)) + obj.min).toFixed(2));
							let num2 = Number(((Math.random() * (obj.max - obj.min)) + num1).toFixed(2));
							newArr[i].push(arr[i], num1, Number(((Math.random() * (obj.max - obj.min)) + obj.min).toFixed(2)), Number(((Math.random() * (obj.max - obj.min)) + obj.min).toFixed(2)), num2, Math.floor(Math.random() * 10000))
						}
					}
				}
				let data = splitData(newArr)
				this.chartOptions = {
					backgroundColor: '#fff',
					animation: false,
					legend: {
						bottom: 10,
						left: 'center',
						data: [title]
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'cross'
						},
						backgroundColor: 'rgba(245, 245, 245, 0.8)',
						borderWidth: 1,
						borderColor: '#ccc',
						padding: 10,
						textStyle: {
							color: '#000'
						},
						position: function(pos, params, el, elRect, size) {
							var obj = {
								top: 10
							};
							obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
							return obj;
						},
						formatter(params) {
							let param = params[0];
							let arr = []
							arr.push(param.data[1], param.data[2], param.data[3], param.data[4])
							arr.sort()
							return [
								'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">',
								'min: ' + arr[0] + '<br/>',
								'max: ' + arr[3] + '<br/>'
							].join('');
						}
					},
					axisPointer: {
						link: {
							xAxisIndex: 'all'
						},
						label: {
							backgroundColor: '#777'
						}
					},
					toolbox: {
						feature: {
							dataZoom: {
								yAxisIndex: false
							},
							brush: {
								type: ['lineX', 'clear']
							}
						}
					},
					brush: {
						xAxisIndex: 'all',
						brushLink: 'all',
						outOfBrush: {
							colorAlpha: 0.1
						}
					},
					grid: [{
							left: '10%',
							right: '8%',
							height: '80%'
						},
						{
							borderWidth: 0,
							left: '10%',
							right: '8%',
							top: '100%',
							height: '0%'
						}
					],
					xAxis: [{
							type: 'category',
							data: data.categoryData,
							scale: true,
							boundaryGap: false,
							axisLine: {
								onZero: false
							},
							splitLine: {
								show: false
							},
							splitNumber: 20,
							min: 'dataMin',
							max: 'dataMax',
							axisPointer: {
								z: 100
							}
						},
						{
							type: 'category',
							gridIndex: 1,
							data: data.categoryData,
							scale: true,
							boundaryGap: false,
							axisLine: {
								onZero: false
							},
							axisTick: {
								show: false
							},
							splitLine: {
								show: false
							},
							axisLabel: {
								show: false
							},
							splitNumber: 20,
							min: 'dataMin',
							max: 'dataMax'
						}
					],
					yAxis: [{
							scale: true,
							splitArea: {
								show: false
							}
						},
						{
							scale: true,
							gridIndex: 1,
							splitNumber: 2,
							axisLabel: {
								show: false
							},
							axisLine: {
								show: false
							},
							axisTick: {
								show: false
							},
							splitLine: {
								show: false
							}
						}
					],
					series: [{
						name: title,
						type: 'candlestick',
						data: data.values,
						itemStyle: {
							color: upColor,
							color0: downColor,
							borderColor: null,
							borderColor0: null
						}
					}]
				}

			}
		}
	};
</script>
<style lang="scss">
	.proportion {
		.el-card__body {
			height: calc(100% - 35px);
			.avue-crud {
				height: calc(100% - 155px);
			}
		}
	}
</style>
<style lang="scss" scoped>
	.map {
		width: 100%;
		height: 500px;
	}
	
	.box {
		height: 100%;
		margin-bottom: 0;
	}
	
	.search-left {
		display: flex;
		height: 33px;
		line-height: 33px;
	}
	
	.el-row {
		height: calc(100% - 20px);
	}
	
	.el-col {
		height: 100%;
		overflow: auto;
	}
	
	.search-tools {
		height: 49px;
		display: flex;
		justify-content: space-between;
		padding: 0 8px;
	}
	
	.search-right {
		display: flex;
	}
	
	.search-tabs {
		height: 33px;
		display: flex;
		align-items: center;
		margin-right: 40px;
	}
	
	.overlay {
		position: absolute;
		width: 200px;
		height: 100%;
		opacity: 0;
		display: flex;
		align-items: center;
		padding-left: 6px;
		.tree-tool {
			height: 34px;
			width: 18px;
			background: #fff;
			box-shadow: 2px 1px 4px #ccc;
			border-top-right-radius: 3px;
			border-bottom-right-radius: 3px;
			cursor: pointer;
			display: flex;
			padding: 6px 0;
			z-index: 9999;
			.tool-line {
				margin-left: 3px;
				height: 100%;
				border-left: 1px solid #ddd;
			}
		}
	}
	
	.overlay:hover {
		opacity: 1;
	}
</style>